﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Collections;

namespace l1cs.server.model.gametime
{
    class L1GameTimeClock
    {
        private static Logger _log = Logger.getLogger( typeof( L1GameTimeClock ).FullName );

        private static L1GameTimeClock _instance;

        private volatile L1GameTime _currentTime = new L1GameTime();

        private L1GameTime _previousTime = null;

        private ArrayList _listeners = ArrayList.Synchronized( new ArrayList() );

        private void TimeUpdater( object state )
        {
            while ( true )
            {
                _previousTime = _currentTime;
                _currentTime = new L1GameTime();
                //_log.info( "ゲーム内時間:" + _currentTime.ToString() );
                notifyChanged( _previousTime.getDateTime(), _currentTime.getDateTime() );
                Thread.Sleep( 500 );
            }
        }

        private void notifyChanged( DateTime prevTime, DateTime curTime )
        {
            if ( prevTime.Month != curTime.Month )
            {
                foreach ( L1GameTimeListener listener in _listeners )
                {
                    listener.onMonthChanged( _currentTime );
                }
            }
            if ( prevTime.Day != curTime.Day )
            {
                foreach ( L1GameTimeListener listener in _listeners )
                {
                    listener.onDayChanged( _currentTime );
                }
            }
            if ( prevTime.Hour != curTime.Hour )
            {
                foreach ( L1GameTimeListener listener in _listeners )
                {
                    listener.onHourChanged( _currentTime );
                }
            }
            if ( prevTime.Minute != curTime.Minute )
            {
                foreach ( L1GameTimeListener listener in _listeners )
                {
                    listener.onMinuteChanged( _currentTime );
                }
            }
        }

        private L1GameTimeClock()
        {
            ThreadPool.QueueUserWorkItem( new WaitCallback( TimeUpdater ) );
        }

        public static void init()
        {
            _instance = new L1GameTimeClock();
        }

        public static L1GameTimeClock getInstance()
        {
            return _instance;
        }

        public L1GameTime currentTime()
        {
            return _currentTime;
        }

        public void addListener( L1GameTimeListener listener )
        {
            _listeners.Add( listener );
        }

        public void removeListener( L1GameTimeListener listener )
        {
            _listeners.Remove( listener );
        }
    }
}
